package com.zixun.main;

import android.graphics.Color;
import android.os.Bundle;
import android.support.v4.app.FragmentActivity;
import android.support.v4.app.FragmentManager;
import android.support.v4.app.FragmentTransaction;
import android.view.KeyEvent;
import android.widget.Toast;

import com.zixun.R;
import com.zixun.db.DatabaseUtil;
import com.zixun.fragment.DoctorFragment;
import com.zixun.fragment.RongCloudFragment;

import java.util.ArrayList;
import java.util.List;

import io.rong.imkit.RongIM;
import io.rong.imlib.RongIMClient;

public class MainActivity extends FragmentActivity {

    private BottomBarLayout bottomBarLayout;
    private List<TabEntity> tabEntityList;
    private String[] tabText = { "咨询", "咨询者"};
    private long exitTime = 0;
    private int[] normalIcon = { R.mipmap.buy, R.mipmap.play};
    private int[] selectIcon = { R.mipmap.buy1, R.mipmap.play1};

    private int normalTextColor = Color.parseColor("#999999");
    private int selectTextColor = Color.parseColor("#fa6e51");
    private FragmentManager fragmentManager;
    private RongCloudFragment rongCloudFragment;
    private DoctorFragment doctorFragment;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);
        fragmentManager = getSupportFragmentManager();
        bottomBarLayout = (BottomBarLayout) findViewById(R.id.bottom_nav);
        setTabSelection(0);
        tabEntityList = new ArrayList<>();
        for (int i = 0; i < tabText.length; i++) {
            TabEntity item = new TabEntity();
            item.setText(tabText[i]);
            item.setNormalIconId(normalIcon[i]);
            item.setSelectIconId(selectIcon[i]);
            tabEntityList.add(item);
        }

        bottomBarLayout.setNormalTextColor(normalTextColor);
        bottomBarLayout.setSelectTextColor(selectTextColor);
        bottomBarLayout.setTabList(tabEntityList);

        bottomBarLayout.setOnItemClickListener(new BottomBarLayout.OnItemClickListener() {
            @Override
            public void onItemClick(int position) {

                setTabSelection(position);
            }
        });
        //"8BIxvl3eejLqfTqqIND5EPaLsO2hFfZho5pEjDnlJaFEh2Q0VR4tYRIR40D/A8+hxP9x4E7GZ7AmD1e1fCHU89kGbcUOn3pI"
        //initRong("eaKj0wuxwZ1R1pbBhhfFEmFvgvLyrQA495z2CdbRPQmChOQjR+YNV9/HiINZpgGTZoDpriOKtCkFzrVx3jMzQm++J0MC+jTd");//
        //initRong("XktulFDsD6nBAxkNc+SzfDTES8siBdw3XROpn+/MNTNvEF9tNaymznyamg5Q/StC4yE2eIvZnBeLi/JsxkpJBsQqaIpzpRgv");//18210774927
        initRong("XOp+yHnjvJAl0SfLjJYx5WFvgvLyrQA495z2CdbRPQlTYmxp2W5Y9LOpCUEMnDTWZoDpriOKtCkFzrVx3jMzQtOpqYh9AWTL");//18210208056

    }

    /**
     * 根据传入的index参数来设置选中的tab页。
     *
     * @param index
     */
    private void setTabSelection(int index) {
        // 开启一个Fragment事务
        FragmentTransaction transaction = fragmentManager.beginTransaction();
        // 先隐藏掉所有的Fragment，以防止有多个Fragment显示在界面上的情况
        hideFragments(transaction);
        switch (index) {
            case 0:
                if (rongCloudFragment == null) {
                    rongCloudFragment = new RongCloudFragment();
                    transaction.add(R.id.main_fragment, rongCloudFragment);
                } else {
                    transaction.show(rongCloudFragment);
                }
                break;
            case 1:
                if (doctorFragment == null) {
                    doctorFragment = new DoctorFragment(MainActivity.this);
                    transaction.add(R.id.main_fragment, doctorFragment);
                } else {
                    transaction.show(doctorFragment);
                }
                break;
            default:
                break;
        }
        transaction.commitAllowingStateLoss();
    }

    private void hideFragments(FragmentTransaction transaction) {
        if (rongCloudFragment != null) {
            transaction.hide(rongCloudFragment);
        }
        if (doctorFragment != null) {
            transaction.hide(doctorFragment);
        }
    }

    private void initRong(final String rong_token) {
        new Thread() {
            @Override
            public void run() {
                RongIM.connect(rong_token, new RongIMClient.ConnectCallback() {
                    @Override
                    public void onTokenIncorrect() {

                    }

                    @Override
                    public void onSuccess(String s) {

                        // 1
                        if (RongIM.getInstance() != null) {
//                            RongIM.getInstance().setCurrentUserInfo(new UserInfo(s, PrefUtils.getDefaults("userName", MainActivity.this),
//                                    Uri.parse(PrefUtils.getDefaults("portraits", MainActivity.this))));
                            RongIM.getInstance().setMessageAttachedUserInfo(true);
                        }
                    }

                    @Override
                    public void onError(RongIMClient.ErrorCode errorCode) {

                    }

                });
            }
        }.start();
    }

    @Override
    public boolean onKeyDown(int keyCode, KeyEvent event) {
        if (keyCode == KeyEvent.KEYCODE_BACK && event.getAction() == KeyEvent.ACTION_DOWN) {
            if ((System.currentTimeMillis() - exitTime) > 2000) {
                Toast.makeText(getApplicationContext(), "再按一次退出程序", Toast.LENGTH_SHORT).show();
                exitTime = System.currentTimeMillis();
            } else {
                finish();
                System.exit(0);
            }
            return true;
        }
        return super.onKeyDown(keyCode, event);
    }
}
